﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace UserServicesCenter
{
    public partial class ServicesCenter : Form
    {

        Thread BackgroundListener;
        int LinstenPoint = 8848;
        IPAddress address = IPAddress.Any;
        Socket mySocket;

        public ServicesCenter()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;

            button1.Text = "Start Linsten";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            BackgroundListener = new Thread(new ThreadStart(StartListen));
            BackgroundListener.Start();
        }

        public void StartListen()
        {
            TcpListener myListener = new TcpListener(new IPEndPoint(address, LinstenPoint));
            myListener.Start();
            AppendLog("Start Listen Point 8848 ! ");
            

            try
            {
               
                // Start listening for connections.
                while (true)
                {
                    mySocket = myListener.AcceptSocket();

                    if (mySocket.Connected)
                    {
                        AppendLog(String.Format("Connect - {0}", mySocket.RemoteEndPoint));//log it, new connectio 
                        AddUser(mySocket.RemoteEndPoint, mySocket);

                        Thread ReceiveProcess = new Thread(new ThreadStart(ReceiveMsg));
                        ReceiveProcess.IsBackground = true;
                        ReceiveProcess.Start();

                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void ReceiveMsg()
        {
            byte[] mybuffer = new byte[1024];
            mySocket.Receive(mybuffer);

            AppendLog(String.Format("The Message:{0}", Encoding.Default.GetString(mybuffer)));
        }



        private void AddUser(EndPoint endPoint, Socket mySocket)
        {
            listView1.Items.Add(new ListViewItem(endPoint.ToString()));

            SendMsg("您已经连接成功！");
        }

        private void SendMsg(string p)
        {
            byte[] mybuffer = Encoding.Default.GetBytes(p);
            mySocket.Send(mybuffer);
            
        }

        private void AddUser(EndPoint endPoint)
        {
            listView1.Items.Add(new ListViewItem(endPoint.ToString()));
            //throw new NotImplementedException();
        }

        private void AppendLog(string par)
        {
            RT_Result.AppendText(par + Environment.NewLine);
        }


    }
}
